package com.txsj.scan.widget.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.txsj.scan.R;

/**
 * @Created by WangChuangJun on 2018/12/6
 * @Describe
 */
public class ScanningDialog extends Dialog {
    private Activity activity;
    private TextView tv_scan_count, tv_end;
    private ImageView iv_translate;

    private Animation animation = null;

    public void setListener(OnScanEndListener listener) {
        this.listener = listener;
    }

    private OnScanEndListener listener;

    public ScanningDialog(Activity context) {
        super(context, R.style.ThemeScanningDialog);
        super.setContentView(R.layout.dialog_scaning);
        setCanceledOnTouchOutside(false);
        this.activity = context;
        initView();
        initData();
    }

    private void initData() {
        tv_scan_count.setText("0");
        initAnimation();
        tv_end.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != listener)listener.onEnd();
            }
        });
    }

    private void initView() {
        iv_translate = (ImageView) findViewById(R.id.iv_translate);
        tv_scan_count = (TextView) findViewById(R.id.tv_scan_count);
        tv_end = (TextView) findViewById(R.id.tv_end);
    }

    private void initAnimation() {
        animation = AnimationUtils.loadAnimation(activity,
                R.anim.loading_animation);
        //设置插值器，让他线性匀速旋转
        animation.setInterpolator(new LinearInterpolator());
    }



    public void show() {
        super.show();
        this.iv_translate.startAnimation(animation);
    }

    /**
     * 更新显示的个数
     * @param count
     */
    public void updateScanCount(long count){
        if (this.isShowing()) {
            tv_scan_count.setText("" + count);
        }
    }

    public interface OnScanEndListener{
        void onEnd();
        void onKeyDownF4();
    }

    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
        boolean result = super.onKeyDown(keyCode, event);
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            result = false;
        }
        if (event.getKeyCode() == KeyEvent.KEYCODE_F4) {//扫码枪的按钮action：KEYCODE_F4
            //扫码枪物理按钮点击
            if (null != listener)listener.onKeyDownF4();
            return true;
        }
        return result;
    }
}
